<?php
/*
 * [fieldset_builder id='FieldsetBuilder' label='fieldset' tableclasses='table-bordered,table-striped,table-hover,table-condensed']
 *
 */

namespace WebApper\Shortcode;

class FieldsetBuilder extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'fieldset_builder';
	protected $defaults = array(
		'id' => null,			// The unique ID to use for the shortcode. Default: none. Required.
		'label' => 'Fieldset',	// The fieldset label to display. Default: 'Fieldset'.
		'tableclasses' => 'table-bordered,table-striped,table-hover,table-condensed',  // Adjust how the DataTable will display. Default: 'table-bordered,table-striped,table-hover,table-condensed'.
	);

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Ouput datatable HTML & Javascript
			?>
            <hr />
            <div class="alert alert-info fade in">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <strong>How To!</strong> Use this tool to create fieldsets, allowing you to group fields together. You can then call fields you added to a fieldset with a shortcode as a group of fields instead of including each field individually. Rows are selectable. Click on the add, edit, or delete button to get started.
            </div>
			<table id="<?php echo $id; ?>_datatable" class="table <?php echo str_replace(",", " ", $tableclasses); ?>">
				<thead>
					<tr>
						<th>ID</th>
						<th>Label</th>
						<th>Fieldset ID</th>
						<th>Description</th>
						<th>Order</th>
					</tr>
				</thead>
				<tbody>
					<?php
					global $wpdb;
					$fieldsetsTable = $wpdb->prefix . 'web_apper_fieldsets';
					$web_apper_fieldsets = $wpdb->get_results(
						'SELECT * FROM ' . $fieldsetsTable,
						'ARRAY_A'
					);
					foreach ( $web_apper_fieldsets as $fieldset ) :
						echo '<tr>',
								 '<td>', $fieldset['ID'], '</td>',
								 '<td>', $fieldset['fieldset_name'], '</td>',
								 '<td>', $fieldset['fieldset_id'], '</td>',
								 '<td>', $fieldset['description'], '</td>',
								 '<td>', $fieldset['fieldset_order'], '</td>',
							 '</tr>';
					endforeach;
					?>
				</tbody>
			</table>
			<script type="text/javascript">
				// Store Commonly manipulated DOM nodes as objects
				nForm = jQuery('#<?php echo $id; ?>');
				nFormTask = jQuery('input[name="web_apper_task"]', nForm);
				nModal = jQuery('.modal', nForm);
				nModalHeader = jQuery('.modal-header h3', nModal)
				nModalBody = jQuery('.modal-body', nModal);
				nModalClose = jQuery('.modal-footer [data-dismiss="modal"]', nModal)
				nModalSaveBtn = jQuery('.modal-footer #save', nModal)
				nModalUpdateBtn = jQuery('.modal-footer #update', nModal)
				nModalDeleteBtn = jQuery('.modal-footer #delete', nModal)
				nModalElements = jQuery('.modal-body>*', nModal);
				nDeleteWarning = jQuery('#deleteWarning', nModal);
				nTable = jQuery('#<?php echo $id; ?>_datatable');
				
				jQuery(document).ready(function($) {
					// Initialize dataTable
					oTable = $(nTable).dataTable({
						<?php
							// Build the sDom parameter for dataTables
							global $template;
							if ( stristr($template, 'fullwidth') ) :
								$spanA = 6; $spanB = 6;
							else :
								$spanA = 4; $spanB = 5;
							endif;
							echo "'sDom': \"<'row'<'span".$spanA."'EC><'span".$spanB."'fl>r>t<'row'<'span".$spanA."'i><'span".$spanB."'p>>\",\n";
						?>
						'sPaginationType': 'bootstrap',
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [ 0 ] } ],
						"aaSorting": [ [4,'asc'] ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0 ]
						},
					});
	
				});
				// Handle response from ajax post
				function parseResponse<?php echo $id; ?>(response) {
					var result = jQuery.parseJSON(response);  // Parse response
					if ( result.success ) {  // If ajax returns a successful save
						if ( result.task == 'add' ) {  // If we added a row
							jQuery('input[name="web_apper_id"]', nForm).val( result.ID );  // Prepend the returned record ID to the array before adding to the dataTable
							var formValues = nForm.getFormValues();  // Get array of form values
							oTable.fnAddDataAndDisplay(formValues);  // Add row to table
							nForm.clearForm();  // Clear form values
						} else if ( result.task == 'update' ) {  // If we updated a row
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							var formValues = nForm.getFormValues();  // Get array of form values
							oTable.fnUpdate( formValues, rowPosition ); // Update the dataTable row
						} else if ( result.task == 'delete' ) {  // If we deleted a row
							nDeleteWarning.css('display', 'none');  // Hide the delete warning
							nModalDeleteBtn.css('display', 'none');  // Hide the modal submit button
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							oTable.fnDeleteRow( rowPosition );
						}
					}
					resetModalButtons();
					nModalBody.prepend(result.htmlalert);  // Show and alert
				}
			</script>
            <?php

		// Configure form settings
			$this->config_form( $atts );  // Check if user has proper privileges

		// Build the form
			$form = new \PFBC\Form($id);
			$form->configure( $this->formConfig );
			$form->addElement(new \PFBC\Element\Hidden('web_apper_form', $id));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_nonce', wp_create_nonce( 'WebApperAwesomeness!87' )));
			$form->addElement(new \PFBC\Element\Hidden('action', 'web_apper' . $this->shortcode));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_task', 'add'));
			// Form Modal header
			$form->addElement(new \PFBC\Element\ModalHeading($label));
			$form->addElement(new \PFBC\Element\HTML('<div id="deleteWarning"><span class="label label-important pull-left">Delete ' . $label . '</span><p>&nbsp;You are about to delete a ' . $label . '. Are you sure you want to do this?</p></div>'));
			// Form Modal body
			$form->addElement(new \PFBC\Element\Hidden('web_apper_id'));
			$form->addElement(new \PFBC\Element\Textbox('Name:', 'fieldset_name', array(
				"required" => 1,
				'placeholder' => 'Fieldset Name',
				'shortDesc' => 'A readable name for the fieldset'
			)));
			$form->addElement(new \PFBC\Element\Textbox('Fieldset ID:', 'fieldset_id', array(
				"required" => 1,
				'placeholder' => 'fieldset-id',
				'shortDesc' => 'A unique ID for the fieldset',
				'longDesc' => 'Must be alphanumeric: contain only lowercase letters, numbers, underscores(_) and/or hyphens(-).',
				"validation" => new \PFBC\Validation\AlphaNumeric
			)));
			$form->addElement(new \PFBC\Element\Textarea('Description:', 'description', array(
				'longDesc' => 'Optional description of the fieldset to be used as a heading. If no description is provided, the fieldset name will be used instead'

			)));
			$form->addElement(new \PFBC\Element\Number('Order:', 'fieldset_order'));
			// Form Modal footer
			$form->addElement(new \PFBC\Element\Button('Save', 'submit', array(
				'id' => 'save',
				'data-loading-text' => 'Saving...'
			)));
			$form->addElement(new \PFBC\Element\Button('Update', 'submit', array(
				'id' => 'update',
				'data-loading-text' => 'Updating...'
			)));
			$form->addElement(new \PFBC\Element\Button('Delete', 'submit', array(
				'id' => 'delete',
				'class' => 'btn btn-danger',
				'data-loading-text' => 'Deleting...'
			)));
            $form->render();  // Output the form

	}

    /**
     * Add new record
     *
     * @since 1.0
     */
	public function add_record() {
		global $wpdb;
		$wpdb->insert( 
			$wpdb->prefix . 'web_apper_fieldsets',
			array( 
				'fieldset_name' => $_POST['fieldset_name'],
				'fieldset_id' => $_POST['fieldset_id'],
				'description' => $_POST['description'],
				'fieldset_order' => $_POST['fieldset_order'],
			), 
			array( '%s', '%s', '%s' ) 
		);
		if ( $wpdb->insert_id ) :	
			return $this->sendResponse( 'Fieldset saved.', 'alert-success', 'Hurray!', true, $wpdb->insert_id );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the fieldset. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Update a record
     *
     * @since 1.0
     */
	public function update_record() {
		global $wpdb;
		$result = $wpdb->update(
			$wpdb->prefix . 'web_apper_fieldsets',
			array( 
				'fieldset_name' => $_POST['fieldset_name'],
				'fieldset_id' => $_POST['fieldset_id'],
				'description' => $_POST['description'],
				'fieldset_order' => $_POST['fieldset_order'],
			), 
			array( 'ID' => $_POST['web_apper_id'] ),
			array( '%s', '%s', '%s' )
		);
		if ( $result === 0 ) :	
			return $this->sendResponse( 'The fieldset was not updated because you haven\'t made any changes.', 'alert-info', 'Heads Up!', true );  // Send Response
		elseif ( $result ) :	
			return $this->sendResponse( 'Fieldset updated.', 'alert-success', 'Hurray!', true );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem updating the fieldset. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Delete a record
     *
     * @since 1.0
     */
	public function delete_record() {
		global $wpdb;
		$fieldsetsTable = $wpdb->prefix . 'web_apper_fieldsets';
		$result = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $fieldsetsTable WHERE id = %d", $_POST['web_apper_id']
			)
		);
		if ( $result ) :	
			return $this->sendResponse( 'Fieldset deleted.', 'alert-success', 'Hurray!', true );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem deleting the fieldset. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}
	
}

$initialize = new FieldsetBuilder(); 

?>